from flask import Blueprint, request, jsonify
from com.util import MailUtil, Rep, RedisUtil
from com import db
from flask_jwt import jwt_required, current_identity
from werkzeug.security import generate_password_hash, check_password_hash

user = Blueprint('user', __name__)


@user.route('/test')
@jwt_required()
def test():
    print("现在的身份：", current_identity)
    user = current_identity
    print('这是用户姓名', user.username)
    result = Rep.Ok()
    print(result)
    return jsonify(result)

# 进行登录
@user.route('/getUserInfo', methods=['GET'])
@jwt_required()
def getUserInfo():
    user = current_identity
    del user.password
    return jsonify(Rep.Ok(data=user.__dict__))


# 进行注册
@user.route('/register', methods=['POST'])
def register():
    body = request.json
    print("这是请求体", body)
    email = body['email']
    code = body['code']
    nickName = body['nickName']
    password = body['password']
    if email is None:
        return Rep.Error("请输入用户邮箱")
    if code is None:
        return Rep.Error("请输入验证码")
    if password is None:
        return Rep.Error("请输入密码")

    oldCode = RedisUtil.getKey("lxhEmail" + email)
    oldCode = str(oldCode, encoding='utf8')
    if oldCode != code:
        return Rep.Error(msg="验证码错误，请重新获取验证码")


    password = generate_password_hash(password)

    # 输入邮箱。密码，注册成功
    con = db.get_db()
    oldUser = con.execute("select * from user where username = ?", [email]).fetchone()
    if oldUser is not None:
        return Rep.Error(msg="您已经注册过了，请登录")
    con.execute("insert into user (username, password, nickName) values (?, ?, ?)", [email, password, nickName])
    con.commit()

    return Rep.Ok("注册成功")

# 进行发送邮箱
@user.route('/sendUserMessage', methods=['POST'])
def send_user_message():
    data = request.json
    print("这是其请求体", data)
    if data is None or data.get('email', None) is None:
        return jsonify(Rep.Error())

    con = db.get_db_dict()
    oldUser = con.execute("select * from user where username = ?", [data['email']]).fetchone()
    if oldUser is not None:
        return Rep.Error(msg="您已经注册过了，请登录")

    # 进行发送邮件的操作
    MailUtil.sendCode([data['email']])
    result = Rep.Ok(msg='验证码发送成功，请您去邮箱进行查看')
    return jsonify(result)
